package com.yupi.mianshiya.job.like;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.mianshiya.mapper.ArticlesMapper;
import com.yupi.mianshiya.model.entity.Articles;
import com.yupi.mianshiya.service.ArticlesService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yupi.mianshiya.service.impl.LikeServiceImpl.LIKE_COUNT_KEY;


//@Component
@Slf4j
public class LikeDataSyncJob {

    String lockKey = "like:sync:lock";

    @Resource
    private RedissonClient redissonClient;



    @Resource
    private ArticlesService articlesService;

    // 每隔10秒同步一次点赞数据
    @Scheduled(fixedRate = 10000)
    public void syncLikeData() {
        RLock lock = redissonClient.getLock(lockKey);

        try {


            // 尝试获取锁，等待2秒，锁超时10秒
            if (lock.tryLock(2, 10, TimeUnit.SECONDS)) {
                log.info("开始同步点赞数据...");
                long startTime = System.currentTimeMillis();

                // 1. 获取所有文章ID
                LambdaQueryWrapper<Articles> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.select(Articles::getId);
                List<Long> articleIds = articlesService.list(queryWrapper).stream().map(Articles::getId).collect(Collectors.toList());

                log.info("需要同步点赞数的文章数量: {}", articleIds.size());



                // 2. 批量准备更新数据
                List<Articles> collect = articleIds.stream().map(articleId -> {
                    long atomicLong = redissonClient.getAtomicLong(StrUtil.format(LIKE_COUNT_KEY, articleId)).get();

                    int likeCount = Math.toIntExact(atomicLong);
                    Articles article = new Articles();
                    article.setId(articleId);
                    article.setLikeCount(likeCount);
                    return article;
                }).collect(Collectors.toList());

                boolean success  = articlesService.updateBatchById(collect);
                if (success) {

                    log.info("成功同步{}篇文章点赞数据，耗时{}ms",
                            collect.size(),
                            System.currentTimeMillis() - startTime);
                }
            }




        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }catch (Exception e) {
            log.error("点赞数据同步任务执行失败", e);
        } finally {
            lock.unlock();
        }
    }


}
